<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'

const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  fromInfo: {
    type: Object,
    default: () => {}
  }
})

const emit = defineEmits<{
  (e: 'update:isShow', value: boolean): void
}>()

const ruleFormRef = ref<any>()
const form = ref<any>({
  item_id: '',
  item_value: '',
  order_no: ''
})
const resetFrom = ref<any>({ item_id: '', item_value: '', order_no: '' })
if (props.title === '修改字典项') {
  form.value.item_id = props.fromInfo.item_id
  form.value.item_value = props.fromInfo.item_value
  form.value.order_no = props.fromInfo.order_no
} else {
  form.value = resetFrom.value
}

interface RuleForm {
  item_id: string
  item_value: string
  order_no: string
}
const formRules = reactive<FormRules<RuleForm>>({
  item_id: [{ required: true, message: '请输入字典项编码' }],
  item_value: [{ required: true, message: '请输入字典项名称' }],
  order_no: [{ required: true, message: '请输入排序' }]
})
const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  form.value = resetFrom.value
  emit('update:isShow', false)
}

const Confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      console.log('submit!', form.value)
      // saveFormFn()
    } else {
      ElMessage({ message: '请输入完整信息', type: 'error' })
    }
  })
  emit('update:isShow', false)
}
</script>
<template>
  <div>
    <el-dialog
      :title="title"
      :model-value="isShow"
      width="500"
      @close="Cancel(ruleFormRef)"
      draggable
      overflow
    >
      <el-form :model="form" :rules="formRules" ref="ruleFormRef" label-width="auto">
        <el-form-item label="字典项编码" prop="item_id">
          <el-input v-model="form.item_id" clearable />
        </el-form-item>
        <el-form-item label="字典项名称" prop="item_value">
          <el-input v-model="form.item_value" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="order_no">
          <el-input v-model="form.order_no" type="number" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="Confirm(ruleFormRef)"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="less"></style>
